package com.demandbreakdown.xiyun.controller;

import com.demandbreakdown.xiyun.common.annotation.ApiLog;
import com.demandbreakdown.xiyun.common.base.Result;
import com.demandbreakdown.xiyun.common.base.ResultUtils;
import com.demandbreakdown.xiyun.model.dto.auth.ForgotPasswordDTO;
import com.demandbreakdown.xiyun.model.dto.auth.SendCaptchaDTO;
import com.demandbreakdown.xiyun.model.dto.user.UserLoginDTO;
import com.demandbreakdown.xiyun.model.dto.user.UserRegisterDTO;
import com.demandbreakdown.xiyun.model.vo.auth.LoginVO;
import com.demandbreakdown.xiyun.service.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 认证授权控制器
 *
 * @author poxz
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Tag(name = "认证授权", description = "用户认证和授权相关接口")
public class AuthController {

    private final AuthService authService;

    @ApiLog("发送邮箱验证码")
    @Operation(summary = "发送邮箱验证码", description = "注册/重置密码前发送6位数字验证码")
    @PostMapping("/send-captcha")
    public Result<Void> sendCaptcha(@Valid @RequestBody SendCaptchaDTO sendCaptchaDTO) {
        authService.sendCaptcha(sendCaptchaDTO);
        return ResultUtils.success();
    }

    @ApiLog(value = "用户注册", desensitize = true)
    @Operation(summary = "用户注册", description = "创建账号并自动登录，需要邮箱验证码")
    @PostMapping("/register")
    public Result<LoginVO> register(@Valid @RequestBody UserRegisterDTO userRegisterDTO) {
        LoginVO loginVO = authService.register(userRegisterDTO);
        return ResultUtils.success(loginVO);
    }

    @ApiLog(value = "用户登录", desensitize = true)
    @Operation(summary = "用户登录", description = "账号+密码换token")
    @PostMapping("/login")
    public Result<LoginVO> login(@Valid @RequestBody UserLoginDTO userLoginDTO) {
        LoginVO loginVO = authService.login(userLoginDTO);
        return ResultUtils.success(loginVO);
    }


    @ApiLog("退出登录")
    @Operation(summary = "退出登录", description = "将token加入黑名单并清除用户会话")
    @DeleteMapping("/logout")
    public Result<Void> logout(@RequestHeader("Authorization") String authorization) {
        String token = authorization.replace("Bearer ", "");
        authService.logout(token);
        return ResultUtils.success();
    }

    @ApiLog(value = "忘记密码", desensitize = true)
    @Operation(summary = "忘记密码", description = "通过邮箱验证码重置密码")
    @PostMapping("/forgot-password")
    public Result<Void> forgotPassword(@Valid @RequestBody ForgotPasswordDTO forgotPasswordDTO) {
        authService.forgotPassword(forgotPasswordDTO);
        return ResultUtils.success();
    }
}